package by.msokoloff.javaweb2015.webapp.page;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.inject.Inject;

import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AbstractAutoCompleteRenderer;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField;
import org.apache.wicket.request.Response;

import by.msokoloff.javaweb2015.datamodel.City;
import by.msokoloff.javaweb2015.services.CityService;
import by.msokoloff.javaweb2015.webapp.page.layout.BaseLayout;

public class OrderPage extends BaseLayout {

	@Inject
	private CityService cityService;

	protected void onInitialize() {
				
		super.onInitialize();
		
		AbstractAutoCompleteRenderer<City> autoCompleteRenderer = new AbstractAutoCompleteRenderer<City>() {
		    
			@Override
			protected final String getTextValue(final City city) {
		        return city.getName() + ", " + city.getCountry().getIsoCode();
		    }
		    
			@Override
			protected final void renderChoice(final City city, final Response response, final String criteria) {
		        response.write(getTextValue(city));
		    }

		     
		};
		
		AutoCompleteTextField<City> actfFrom = new AutoCompleteTextField<City>("from", autoCompleteRenderer) {

			@Override
			protected Iterator<City> getChoices(String input) {
				
				if (input.length() < 3) {
					List<City> emptyList = new ArrayList<City>();
					return emptyList.iterator();
				}
				
				return cityService.getStartingWith(input, 20).iterator();
			}


		};
		
		AutoCompleteTextField<City> actfTo = new AutoCompleteTextField<City>("to", autoCompleteRenderer) {

			@Override
			protected Iterator<City> getChoices(String input) {
				
				if (input.length() < 3) {
					List<City> emptyList = new ArrayList<City>();
					return emptyList.iterator();
				}
				
				return cityService.getStartingWith(input, 20).iterator();
			}


		};
		
		add(actfFrom);
		add(actfTo);
		
	};

}
